package lab

import (
	"pdocker/docker"
	"pdocker/task"
	"pdocker/tool/sql"
	"pdocker/types"
	"time"

	log "github.com/sirupsen/logrus"
)

var (
	timerList map[string]*time.Timer
)

type (
	Task struct {
		Task       task.Task          `json:",omitempty"`
		Containers []docker.LabDocker `json:",omitempty"`
	}
	TaskTable struct {
		Id   int  `gorm:"primaryKey"`
		Data Task `gorm:"serializer:json"`
	}
	TaskCreateModel struct {
		TaskId           string `json:"taskid,omitempty"`
		CallBack         string `json:"callback,omitempty"`
		DestroyTimeStamp int64  `json:"destroytimestamp,omitempty"`
		LabDocker        []docker.LabDocker
	}

	TaskUpdateModel struct {
		TaskId           string `json:"taskid,omitempty"`
		DestroyTimeStamp int64  `json:"destroytimestamp,omitempty"`
	}

	TaskDeleteModel struct {
		TaskId string `json:"taskid,omitempty"`
	}
)

func init() {
	timerList = make(map[string]*time.Timer)
	initTable()
	initAll()
}

func initTable() {
	err := sql.PgDB.AutoMigrate(&TaskTable{})
	if err != nil {
		log.Errorln(err)
	} else {
		log.Debugf("创建表 lab task table:")
	}
}
func initAll() {
	var rows []TaskTable
	err := sql.PgDB.Find(&rows).Error
	if err != nil {
		log.Error(err)
	}
	for _, row := range rows {
		var table TaskTable
		table.Data = row.Data
		var control types.TaskControl = &table.Data
		control.Init()
	}
}
